<template>
	<view>
	<!-- 导航栏已注释，移除白顶 -->
	<!-- <o-navbarx :back="false" color="#000000" :isback="true"  background="transparent">
		<template #left_conent>
			<view class="pad-lr-20 pad-tb-14 display-sb align-items" @click="selectuser" v-if="is_shop==1">
				<image src="/static/img/qie.png" class="proudct-item-icon-24" mode=""></image>
				<view class="ml10 fontSize-28">{{is_user?'切换商户':'切换用户'}}</view>
			</view>
		</template>
	</o-navbarx> -->
	<view class="pad-lr-30 pad-tb-20 poRe top_view" :class="is_user?'bgfff':'bgf6'" style="padding-top: 0; margin-top: 0;">
		<view class="display-sb align-items">
			<view class="display align-items">
				<image :src="info?.avatar_text" class="proudct-item-icon-6 border-50" mode="" v-show="is_user"></image>
				<image :src="info?.image_text" class="proudct-item-icon-6 border-50" mode="" v-show="!is_user"></image>
				<view class="ml20">
					<view class="fontSize-40">{{is_user?decodeHtmlEntities(info?.nickname):decodeHtmlEntities(info?.name)}}</view>
					<view class="mar-top-22 fontSize-28 display align-items">{{is_user?info?.mobile:info?.phone}} 
					<image src="/static/img/icon_fuzhi.png" class="proudct-item-icon ml12" @click="copy(info?.phone)" ></image>
					</view>
				</view>
			</view>
			<!-- <view class="col-f fontSize-26 radius-26 xiu_btn text-align-center ml20" v-show="!is_user" @click="downshare">下载分享码</view> -->
			<view class="col-f fontSize-26 radius-26 xiu_btn text-align-center" @click="goinfo">修改资料</view>
		</view>
		<!-- <view class="jifen_view poRe mar-top-40" v-show="is_user">
			<image src="/static/img/panel_jifen.png" class="width-100 height-100 bgimg_top poAb left-0" mode=""></image>
			<view class="poRe display-sb align-items pad-lr-30 padtop40" @click="gointegral">
				<view class="col-f">
					<view class="fontSize-26">余额</view>
					<view class="fontSize-30 mar-top-10">{{info?.money}}</view>
				</view>
				<view class="bgfff radius-26 pad-tb-6 pad-lr-16"><text class="cz_text">去提现</text></view>
			</view>
		</view> -->
		<view class="display-sb align-items mar-top-20 pad-tb-40 flex-wrap" v-if="is_user">
			<view class="width-33" @click="gobalance(1)">
				<view class="fontSize-26 display align-items">余额 <image src="/static/img/icon_youjiantou_.png" class="wid-hig-24 ml4"></image></view>
				<view class="fontSize-30 mar-top-6">{{info?.money}}</view>
			</view>
			<view class="width-33" @click="goScore" v-if="hasPosGoods">
				<view class="fontSize-26 display align-items">积分 <image src="/static/img/icon_youjiantou_.png" class="wid-hig-24 ml4"></image></view>
				<view class="fontSize-30 mar-top-6">{{info?.score || 0}}</view>
			</view>
			<!-- <view class="width-33">
				<view class="fontSize-26">购返池</view>
				<view class="fontSize-30 mar-top-6">{{info?.back_buy_money}}</view>
			</view> -->

		</view>
	</view>
	<view class="pad-lr-30" v-show="is_user">
		<view class="bgfff radius-16 mar-top-40 pad-lr-30 pad-tb-30">
			<view class="display-sb align-items">
				<view class="fontSize-30">我的订单</view>
				<view class="display align-items" @click="goorderlist(0,1)">
					<view class="fontSize-26">全部</view>
					<image src="/static/img/icon_jiantou_18.png" class="ml10 wid-hig-28" mode=""></image>
				</view>
			</view>
			<view class="mar-top-30 display-sb align-items">
				<view class="width-15 text-align-center poRe" v-for="item in order_state" :key="item.id" @click="goorderlist(item.state,1)">
					<tm-badge :count="item.num" :maxCount="99" color="red" linear="top">
					<image :src="item.img" class="proudct-item-icon-28"></image>
					<view class="text-align-center fontSize-26 mar-top-8">{{item.name}}</view>
					</tm-badge>
				</view>
			</view>
		</view>
		<view class="bgfff radius-16 mar-top-20 pad-lr-30 pad-tb-30">
			<view class="display-sb align-items">
				<view class="fontSize-30">常用功能</view>
			</view>
			<view class="display align-items flex-wrap">
				<view class="width-25 mar-top-30 text-align-center" v-for="item in tool_list" :key="item.id" @click="gopath(item.path,item.id)">
					<image :src="item.img" class="proudct-item-icon-28"></image>
					<view class="text-align-center fontSize-26 mar-top-8">{{item.name}}</view>
				</view>
				<!-- 我的机具 - 只有有POS机商品时才显示 -->
				<view class="width-25 mar-top-30 text-align-center" v-if="hasPosGoods" @click="goMachine">
					<image src="/static/img/icon_jiju.png" class="proudct-item-icon-28"></image>
					<view class="text-align-center fontSize-26 mar-top-8">我的机具</view>
				</view>
			</view>
		</view>
	</view>
	<!-- 线下用户显示 -->
	<view class="pad-lr-40 over-hid" v-show="!is_user">
		<view class="mar-top-20 pad-tb-24 pad-lr-40 yue_view radius-16 poRe">
			<view class="mar-top-8">
				<view class="fontSize-26 col-6">余额</view>
				<view class="fontSize-40 fontBold col-C9951C mar-top-6">{{info?.money}}</view>
			</view>
			<view class="poAb bgfff right-0 top-50 ti_btn fontSize-28 pad-lr-16 pad-tb-10 col-C9951C" @click="gobalance(2)">
				去提现
			</view>
			<view class="yue_xian mar-top-28"></view>
			<view class="display-sb align-items mar-top-24">
				<view class="">
					<view class="fontSize-24 col-6">待到账金额</view>
					<view class="fontSize-30 col-C9951C mar-top-6">{{sell_money?.pending_money}}</view>
				</view>
				<view class="">
					<view class="fontSize-24 col-6">本月销售额</view>
					<view class="fontSize-30  col-C9951C mar-top-6">{{sell_money?.month_sell_money}}</view>
				</view>
				<view class="">
					<view class="fontSize-24 col-6">总销售额</view>
					<view class="fontSize-30  col-C9951C mar-top-6">{{sell_money?.total_sell_money}}</view>
				</view>
			</view>
		</view>
		
	</view>
		<view class="bgfff bottom_view mar-top-24" v-show="!is_user">
			<view class="pad-tb-40 display-sb align-items border_bottom_F1" @click="goorderlist(0,1)">
				<view class="display align-items">
					<image src="/static/img/icon_dingdanliebiao.png" class="proudct-item-icon-28" mode=""></image>
					<view class="ml20 fontSize-28">订单列表</view>
				</view>
				<image src="/static/img/icon1.png" class="proudct-item-icon" mode=""></image>
			</view>
			<view class="pad-tb-40 display-sb align-items border_bottom_F1" @click="gogoodsmanage">
				<view class="display align-items">
					<image src="/static/img/icon_shnagpinguanli.png" class="proudct-item-icon-28" mode=""></image>
					<view class="ml20 fontSize-28">商品管理</view>
				</view>
				<image src="/static/img/icon1.png" class="proudct-item-icon" mode=""></image>
			</view>
			<view class="pad-tb-40 display-sb align-items border_bottom_F1" @click="gocode">
				<view class="display align-items">
					<image src="/static/img/icon_kefu1.png" class="proudct-item-icon-28" mode=""></image>
					<view class="ml20 fontSize-28">联系客服</view>
				</view>
				<image src="/static/img/icon1.png" class="proudct-item-icon" mode=""></image>
			</view>
		</view>
	<view class="text-align-center fontSize-28 col-6 poAb bottom-20 width-100">
		{{version}}
	</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import {user,getshopInfo,cutPortType,getParams,batchUnfreezeIncome,batchUnfreezeRegionCommission,checkPosGoods} from '@/utils/api'
import { onLoad, onShow } from '@dcloudio/uni-app';

// HTML 实体解码函数
const decodeHtmlEntities = (str: string) => {
	if (!str) return str;
	return str.replace(/&amp;/g, '&');
};
onLoad(()=>{
	// #ifdef MP-WEIXIN
	const accountInfo = wx.getAccountInfoSync();
	version.value = accountInfo.miniProgram.version;
	// #endif
	
	// #ifdef H5
	version.value = 'H5版本';
	// #endif
})
const version = ref('1.0.0')
onShow(async ()=>{
	if(is_user.value){
		// 先解冻符合条件的收益，再获取用户信息
		await _autoUnfreezeIncome()
		// 区域代理佣金由定时任务自动解冻，不需要手动触发
		_user_info()
	}else{
		_merchants_index()
	}
	uni.$on('updatashopinfo',()=>{
		_merchants_index()
	})
	// _getParams() // 商家入驻功能已注释
})
const info = ref()
const is_shop = ref(0)//是否店铺 1是 0 不是
const hasPosGoods = ref(false) // 商城中是否有is_pos=1的商品

const _user_info =() =>{
	user().then(res=>{
		if(res.code==1){
				info.value = res.data.user
				is_shop.value = res.data.is_shop
				order_state.value[0].num = res.data.order_count.dfk
				order_state.value[1].num = res.data.order_count.dfh
				order_state.value[2].num = res.data.order_count.dsh
				// order_state.value[3].num = res.data.order_count.sh
				// tool_list.value[7].path='/mypages/paycode/paycode?is_set_password='+info.value.is_set_password
				
				// 保存用户信息到本地存储，供积分页面使用
				uni.setStorageSync('userInfo', res.data.user);
				
				// 检查商城中是否有is_pos=1的商品
				_checkPosGoods();
		}
	})
}

// 检查商城中是否有is_pos=1的商品
const _checkPosGoods = () => {
	checkPosGoods().then(res => {
		if (res.code === 1) {
			hasPosGoods.value = res.data.has_pos_goods;
		}
	}).catch(error => {
		console.error('检查POS商品失败:', error);
		hasPosGoods.value = false;
	});
}
// 商家入驻功能已注释
// const _getParams=()=>{
// 	getParams({fields:'enter_switch'}).then(res=>{
// 		if(res.code==1){
// 			if(res.data.enter_switch!='0'){
// 				if(tool_list.value.filter(item=>{return item.id==8}).length==0){
// 					tool_list.value.push({img:'/static/img/icon_shangjiaruzhu.png',name:'商家入驻',id:8,path:'/mypages/shopSettled/shopSettled'})
// 				}
// 			}else{
// 				tool_list.value = tool_list.value.filter(item=>{return item.id!=8})
// 			}
// 		}
// 	})
// }
const is_user = ref(true)//true-用户 false-商户
const order_state = ref([
	{img:'/static/img/icon_daizhifu.png',name:'待支付',id:1,state:1,num:''},
	{img:'/static/img/icon_daifahuo.png',name:'待发货',id:3,state:2,num:''},
	{img:'/static/img/icon_daishouhuo.png',name:'待收货',id:4,state:3,num:''},
	{img:'/static/img/icon_daipingjia.png',name:'已完成',id:5,state:4,num:''}
])
const tool_list = ref([
	{img:'/static/img/icon_wodeshoucang.png',name:'我的收藏',id:1,path:'/mypages/collectlist/collectlist'},
	{img:'/static/img/icon_wodepingjia.png',name:'我的评价',id:2,path:'/mypages/evaluatelist/evaluatelist'},
	{img:'/static/img/icon_shouhuodizhi.png',name:'收货地址',id:3,path:'/indexpages/addresslist/addresslist'},
	{img:'/static/img/icon_xianjinzhifu.png',name:'银行卡',id:17,path:'/mypages/bankcardlist/bankcardlist'},
	{img:'/static/img/icon_lianxikefu.png',name:'联系客服',id:4,path:'/mypages/contact/contact?type=1'},
	{img:'/static/img/icon_shouhou.png',name:'售后',id:5,path:'/mypages/servicelist/servicelist'},
	// {img:'/static/img/icon_jianyifankui.png',name:'建议反馈',id:6,path:'/mypages/feedback/feedback'},
	// {img:'/static/img/icon_saoyisao1.png',name:'我的金币',id:7,path:'/mypages/code/code'},
	// {img:'/static/img/icon_jifenfukuanma_30.png',name:'我的推荐码',id:6,path:'/mypages/suncode/suncode'},
	// {img:'/static/img/icon_wodetuandui.png',name:'我的直推',id:9,path:'/mypages/userteam/userteam'},
	// {img:'/static/img/icon_zhituichi.png',name:'直推池',id:10,path:'/mypages/ZTpool/ZTpool'},
	// =============== 系统功能 ===============
	{img:'/static/img/icon_wodetuandui.png',name:'我的团队',id:11,path:'/mypages/linkage/team/team'},
	{img:'/static/img/icon_shouhou.png',name:'我的收益',id:12,path:'/mypages/linkage/income/income'},
	{img:'/static/img/icon_jifenfukuanma_30.png',name:'邀请分享码',id:13,path:'/mypages/linkage/invite/invite'},
	{img:'/static/img/icon_fenhongmingxi.png',name:'分红明细',id:16,path:'/mypages/linkage/dividend/dividend'},
	{img:'/static/img/icon_paihangbang.png',name:'激活排行榜',id:15,path:'/mypages/linkage/ranking/ranking'},
	// =============== 区域代理功能 ===============
	{img:'/static/img/icon_shangjiaruzhu.png',name:'区域代理商',id:14,path:'/mypages/region/agent/agent'},

])
//商户信息
const sell_money = ref({
	month_sell_money: 0,
	total_sell_money: 0,
	pending_money:0
})
const _merchants_index =() =>{
	getshopInfo().then(res=>{
		info.value = res.data.shop
		is_shop.value = 1
		sell_money.value.month_sell_money = res.data.data.month_sell_money
		sell_money.value.total_sell_money = res.data.data.total_sell_money
		sell_money.value.pending_money = res.data.data.pending_money
	})
}
//切换角色
const selectuser =() =>{
	is_user.value = !is_user.value
	uni.setStorageSync('is_user',is_user.value)
	cutPortType().then(res=>{
		
	})
	if(!is_user.value){
		_merchants_index()
	}else{
		_user_info()
	}
}
const goinfo = () =>{
	if(is_user.value){
	// 对 JSON 字符串进行 URL 编码，避免特殊字符（如 &）破坏 URL 参数
	const userInfoStr = encodeURIComponent(JSON.stringify(info.value));
	uni.navigateTo({
		url:'/mypages/info/info?info='+userInfoStr
	})
	}else{
		uni.navigateTo({
			url:'/mypages/shopinfo/shopinfo'
		})
	}
}
const goorderlist =(state:number,type:number) =>{
	if(type==2){
		handleBook()
	}else{
		uni.navigateTo({
			url:'/mypages/orderlist/orderlist?state='+state+'&type='+type
		})
	}
}
const gopath =(path:string,id:number) =>{
	uni.navigateTo({
		url:path
	})
}
const copy =(phone:string) =>{
	uni.setClipboardData({
		data:phone,
		success() {
			uni.showToast({
				title:'已复制',
				icon:'success'
			})
		}
	})
}
const gocode = () =>{
	uni.navigateTo({
		url:'/mypages/contact/contact?type=1'
	})
}
const gobalance = (type) =>{
	uni.navigateTo({
		url:'/mypages/balance/balance?type='+type+'&num='+info.value.money+'&is_withdraw='+info.value.is_withdraw
	})
}
const goScore = () =>{
	uni.navigateTo({
		url:'/mypages/score/score'
	})
}
const goMachine = () =>{
	uni.navigateTo({
		url:'/pages/machine-bind/machine-bind'
	})
}
const gogoodsmanage=()=>{
	uni.navigateTo({
		url:'/mypages/goodsmanage/goodsmanage'
	})
}
const handleBook = () => {
  let id = "J45DVugB-jpKDSsdm3pqFdLghl0bcl8z9hSAIvmUoYk"; // 替换你自己的模板ID 模板详情那里就有模板ID
  uni.requestSubscribeMessage({
    tmplIds: [id],
    success(res) {
      if (res[id] !== "accept") {
        // 用户未授权或选择拒绝，引导前往设置页面
        uni.showModal({
          title: "订阅失败",
          content: "您已设置不再询问，请前往设置开启订阅提醒。",
          confirmText: "去设置",
          success(modalRes) {
            if (modalRes.confirm) {
              openSetting();
            } else {
              uni.showToast({
                title: "您可能错过重要通知",
                icon: "none",
              });
			  uni.navigateTo({
			  	url:'/mypages/orderlist/orderlist?state=0&type=1'
			  })
            }
          },
        });
      } else {
        uni.showToast({
          title: "订阅成功",
          icon: "success",
        });
		uni.navigateTo({
			url:'/mypages/orderlist/orderlist?state=0&type=1'
		})
      }
    },
  });
};
const openSetting = () => {
  uni.openSetting({
    success(res) {
      console.log("设置界面返回：", res);
      if (res.subscriptionsSetting) {
        console.log("订阅消息授权状态：", res.subscriptionsSetting);
      }
    },
    fail(err) {
      console.error("打开设置失败：", err);
    },
	complete() {
		uni.navigateTo({
			url:'/mypages/orderlist/orderlist?state=0&type=1'
		})
	}
  });
};

// 自动解冻符合条件的收益
const _autoUnfreezeIncome = async () => {
  try {
    const res = await batchUnfreezeIncome({});
    if (res.code === 1) {
      console.log('自动解冻结果:', res.msg);
    }
    return res;
  } catch (error) {
    console.error('自动解冻失败:', error);
    return { code: 0, msg: '解冻失败' };
  }
};

// 自动解冻区域代理佣金
const _autoUnfreezeRegionCommission = async () => {
  try {
    const res = await batchUnfreezeRegionCommission({});
    if (res.code === 1) {
      console.log('区域佣金自动解冻结果:', res.msg);
    }
    return res;
  } catch (error) {
    console.error('区域佣金自动解冻失败:', error);
    return { code: 0, msg: '解冻失败' };
  }
};

</script>

<style lang="scss">
@import 'my.scss';
</style>
